package com.fhj.movie.fragment;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONObject;

import android.R.anim;
import android.R.integer;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.fhj.movie.activity.FHCityListActivity;
import com.fhj.movie.activity.FHFilmDetailActivity;
import com.fhj.movie.adapter.FilmCurListAdapter;
import com.fhj.movie.adapter.FilmFurListAdapter;
import com.fhj.movie.adapter.FilmGalleryAdapter;
import com.fhj.movie.entity.FilmEntity;
import com.fhj.movie.interfaces.CallbackInterface;
import com.fhj.movie.interfaces.MyApplication;
import com.fhj.movie_fhj_01.R;
import com.fhj.utils.HttpConnectionUtils;
import com.fhj.utils.JsonUtils;
import com.fhj.utils.Queue;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

public class FhFilmFragment extends Fragment implements OnClickListener,
		OnCheckedChangeListener, OnItemClickListener,
		android.widget.CompoundButton.OnCheckedChangeListener {

	private int type;// 接口请求参数，0表示正在热映，1表示即将上映

	private PullToRefreshListView pToRefreshListView;
	private ListView fimListView;

	private TextView cityBtn;// 标题栏城市名称
	private ViewPager viewPager;

	private RadioGroup radioGroup;
	private RadioButton currentButton;
	private RadioButton furtureButton;

	private CheckBox checkBox;

	private FilmCurListAdapter curAdapter;
	private FilmFurListAdapter furAdapter;
	private FilmGalleryAdapter galleryAdapter;

	private List<View> imgs;

	private View ret = null;

	private Gallery gallery;
	private LinearLayout layout;

	private LinkedList<FilmEntity> films;

	private String cityName;
	private int cityCode;

	private LinearLayout loading;

	public FhFilmFragment() {
		// TODO Auto-generated constructor stub
	}

	int tag = 0;
	int isGallery = 0;

	@SuppressLint("NewApi")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		ret = inflater.inflate(R.layout.film_fragment_layout, container, false);
		View view = inflater.inflate(R.layout.film_listview_header, null);
		viewPager = (ViewPager) view.findViewById(R.id.film_lvheader_viewpager);
		cityBtn = (TextView) ret.findViewById(R.id.btn_current_city);
		radioGroup = (RadioGroup) ret.findViewById(R.id.film_rg_change);
		currentButton = (RadioButton) ret.findViewById(R.id.film_rbtn1);
		furtureButton = (RadioButton) ret.findViewById(R.id.film_rbtn2);

		checkBox = (CheckBox) ret.findViewById(R.id.header_bar_gallery);

		gallery = (Gallery) ret.findViewById(R.id.film_gallery_gly);
		layout = (LinearLayout) ret.findViewById(R.id.film_gallery_layout);
		loading = (LinearLayout) ret.findViewById(R.id.fh_huoqu_layout);
		rotate = (ImageView) ret.findViewById(R.id.fh_rotate_img);
		imgRotate = AnimationUtils.loadAnimation(getActivity(),
				R.anim.load_rotate);
		if (tag == 0) {
			rotate.setAnimation(imgRotate);

		}
		ImageView imgOne = new ImageView(getActivity());
		ImageView imgTwo = new ImageView(getActivity());
		ImageView imgThree = new ImageView(getActivity());
		fimListView = (ListView) ret.findViewById(R.id.film_listview);

		imgOne.setBackground(getResources().getDrawable(R.drawable.bg_bg));
		imgTwo.setBackground(getResources().getDrawable(R.drawable.bg_bg));
		imgThree.setBackground(getResources().getDrawable(R.drawable.bg_bg));
		imgs = new ArrayList<View>();
		imgs.add(imgOne);
		imgs.add(imgTwo);
		imgs.add(imgThree);
		viewPager.setAdapter(new FilmViewPagerAdapter());
		fimListView.addHeaderView(view);

		/* 获取当前城市 */
		MyApplication application = (MyApplication) getActivity()
				.getApplication();
		cityName = application.getCityName();
		cityCode = application.getCityCode();
		Log.d("currentCity", cityName + "," + cityCode);
		cityBtn.setText(cityName);

		getData(type, cityCode);

		// curAdapter = new FilmCurListAdapter(getActivity(),films);
		// furAdapter = new FilmFurListAdapter(getActivity(), films);
		// galleryAdapter = new FilmGalleryAdapter(getActivity());
		// fimListView.setAdapter(curAdapter);
		fimListView.setOnItemClickListener(this);
		cityBtn.setOnClickListener(this);
		radioGroup.setOnCheckedChangeListener(this);
		checkBox.setOnCheckedChangeListener(this);
	    gallery.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getActivity(),FHFilmDetailActivity.class);
				intent.putExtra("type", type);

				if(type==0)
					intent.putExtra("movieId", filmEntitiesCur.get(arg2).getId());
				else if(type==1){
					intent.putExtra("movieId", filmEntitiesFur.get(arg2).getId());
				}
				startActivity(intent);
				
			}
		});

		
		gallery.setOnItemClickListener(this);
		return ret;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	private LinkedList<FilmEntity> filmEntitiesCur;
	private LinkedList<FilmEntity> filmEntitiesFur;
	private Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			int what = msg.what;
			switch (what) {

			case 1:
				if (msg.obj instanceof LinkedList<?>) {
					filmEntitiesCur = (LinkedList<FilmEntity>) msg.obj;

					curAdapter = new FilmCurListAdapter(getActivity(),
							filmEntitiesCur);
					fimListView.setAdapter(curAdapter);
				}
				break;
			case 2:
				if (msg.obj instanceof LinkedList<?>) {
					filmEntitiesFur = (LinkedList<FilmEntity>) msg.obj;
					furAdapter = new FilmFurListAdapter(getActivity(),
							filmEntitiesFur);
					fimListView.setAdapter(furAdapter);
				}
				break;
			case 3:
				if (msg.obj instanceof LinkedList<?>) {
					galleryAdapter = new FilmGalleryAdapter(getActivity(),
							filmEntitiesCur);
					gallery.setAdapter(galleryAdapter);
					Log.i("hhhhhh",
							"--------------------" + filmEntitiesCur.toString());
				}
				break;
			case 4:
				if (msg.obj instanceof LinkedList<?>) {
					galleryAdapter = new FilmGalleryAdapter(getActivity(),
							filmEntitiesFur);
					gallery.setAdapter(galleryAdapter);
				}
				break;
			}

		};
	};

	private ImageView rotate;

	private Animation imgRotate;

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int id = v.getId();
		switch (id) {
		case R.id.btn_current_city:

			Intent intent = new Intent(getActivity(), FHCityListActivity.class);
			startActivityForResult(intent, 1);
			break;

		default:
			break;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub

		if (resultCode == android.app.Activity.RESULT_OK) {
			cityBtn.setText(data.getStringExtra("cityName"));

			getData(type, cityCode);
		}

	}

	class FilmViewPagerAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return imgs.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			// TODO Auto-generated method stub
			return arg0 == arg1;
		}

		@Override
		public Object instantiateItem(View container, int position) {
			// TODO Auto-generated method stub
			((ViewPager) container).addView(imgs.get(position));
			return imgs.get(position);
		}

	}

	public void getData(final int typeId, int cityId) {
		HttpConnectionUtils.getFilmData(getActivity(), typeId, cityId,
				new CallbackInterface() {

					@Override
					public void JsonCallback(JSONObject object) {
						// TODO Auto-generated method stub
						tag = 1;
						rotate.clearAnimation();
						loading.setVisibility(View.GONE);

						Log.i("filmJson", object.toString());
						films = JsonUtils.parseFilms(object);
						if (films != null) {
							if (typeId == 0) {
								if (isGallery == 0) {
									Message message = handler.obtainMessage(1);
									message.obj = films;
									handler.sendMessage(message);
								} else {
									Message message = handler.obtainMessage(3);
									message.obj = films;
									handler.sendMessage(message);
								}

							} else {
								if (isGallery == 0) {
									Message message = handler.obtainMessage(2);
									message.obj = films;
									handler.sendMessage(message);
								} else {
									Message message = handler.obtainMessage(4);
									message.obj = films;
									handler.sendMessage(message);
								}
							}
						}
						Log.d("films", films.toString());

					}
				});
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		// TODO Auto-generated method stub
	
		if (checkedId == currentButton.getId()) {
			type = 0;
			// TODO 加载数据
			if (filmEntitiesCur == null)
				getData(type, cityCode);
			else if (isGallery == 0) {
				curAdapter = new FilmCurListAdapter(getActivity(),
						filmEntitiesCur);
				fimListView.setAdapter(curAdapter);
			} else if (isGallery == 1) {
				galleryAdapter = new FilmGalleryAdapter(getActivity(),
						filmEntitiesCur);
				gallery.setAdapter(galleryAdapter);
			}

		} else if (checkedId == furtureButton.getId()) {
			type = 1;
			// TODO 加载数据
			if (filmEntitiesFur == null)
				getData(type, cityCode);
			else if (isGallery == 0) {
				furAdapter = new FilmFurListAdapter(getActivity(),
						filmEntitiesFur);
				fimListView.setAdapter(furAdapter);
			} else if (isGallery == 1) {
				galleryAdapter = new FilmGalleryAdapter(getActivity(),
						filmEntitiesFur);
				gallery.setAdapter(galleryAdapter);

			}

		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

		// TODO 获取当前项的电影信息，传进intent

		Intent intent = new Intent(getActivity(), FHFilmDetailActivity.class);
		
		intent.putExtra("type", type);
		int movieId=-1;
		if (type == 0&&isGallery==0) {
			movieId = filmEntitiesCur.get(arg2-fimListView.getHeaderViewsCount()).getId();

		} else if(type==1&&isGallery==1){
			movieId = filmEntitiesFur.get(arg2-fimListView.getHeaderViewsCount()).getId();
		}
		intent.putExtra("movieId", movieId);
		
		startActivity(intent);

	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		// TODO Auto-generated method stub
		if (isChecked) {
			isGallery = 1;
			fimListView.setVisibility(View.GONE);
			layout.setVisibility(View.VISIBLE);
			if ((type == 0 && filmEntitiesCur == null)
					|| (type == 1 && filmEntitiesFur == null)) {
				layout.setVisibility(View.VISIBLE);
				rotate.setAnimation(imgRotate);
				getData(type, cityCode);
			} else if (type == 0 && filmEntitiesCur != null) {
				galleryAdapter = new FilmGalleryAdapter(getActivity(),
						filmEntitiesCur);
				gallery.setAdapter(galleryAdapter);
				Log.i("hhhhhh",
						"--------------------" + filmEntitiesCur.toString());

			} else if (type == 1 && filmEntitiesFur != null) {
				galleryAdapter = new FilmGalleryAdapter(getActivity(),
						filmEntitiesFur);
				gallery.setAdapter(galleryAdapter);
			}

		} else {
			isGallery = 0;
			layout.setVisibility(View.GONE);
			fimListView.setVisibility(View.VISIBLE);
			if ((type == 0 && filmEntitiesFur == null) || type == 1
					&& filmEntitiesFur == null) {
				layout.setVisibility(View.VISIBLE);
				rotate.setAnimation(imgRotate);
				getData(type, cityCode);
			} else if (type == 0 && filmEntitiesCur != null) {
				curAdapter = new FilmCurListAdapter(getActivity(),
						filmEntitiesCur);
				fimListView.setAdapter(curAdapter);

			} else if (type == 1 && filmEntitiesFur != null) {
				furAdapter = new FilmFurListAdapter(getActivity(),
						filmEntitiesFur);
				fimListView.setAdapter(furAdapter);
			}
		}
	}

	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		super.onDestroyView();
}

}
